package net.edu_soft.ec.asset.controller;

import com.google.code.kaptcha.Constants;
import net.edu_soft.ec.asset.pojo.UserInfo;
import net.edu_soft.ec.common.util.PuingUtil;
import net.edu_soft.ec.common.util.ResultVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.Session;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@RestController
public class BaseController {


    @RequestMapping(value = "/login")
    public ResultVo login( String username,String password) throws Exception {
        PuingUtil.isEmpty("登录账号不能为空",username);
        PuingUtil.isEmpty("密码不能为空",password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 开启在会话期间记住我
        token.setRememberMe(true);
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        System.out.println("isRemembered: " + SecurityUtils.getSubject().isRemembered());
        System.out.println("isAuthenticated:" + SecurityUtils.getSubject().isAuthenticated());
        try {
            /*if (!onAccessDenied(request, response)) {
                return "验证码为空或错误";
            }*/
            // 提交shiro认证授权
            subject.login(token);
            if (subject.isAuthenticated()) {
                return ResultVo.succeed("用户成功登录！", null);// 验证成功
            } else {
                return ResultVo.failed(500, "用户信息验证错误", null);// 验证失败
            }
        } catch (IncorrectCredentialsException e) {
            return ResultVo.failed(400, "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.", null);
        } catch (ExcessiveAttemptsException e) {
            return ResultVo.failed(400, "登录失败次数过多" + e.getMessage(), null);
        } catch (LockedAccountException e) {
            return ResultVo.failed(400, "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked." + e.getMessage(), null);
        } catch (DisabledAccountException e) {
            return ResultVo.failed(400, "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.", null);
        } catch (ExpiredCredentialsException e) {
            return ResultVo.failed(400, "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.", null);
        } catch (UnknownAccountException e) {
            return ResultVo.failed(400, "帐号不存在. There is no user with username of " + token.getPrincipal(), null);
        } catch (UnauthorizedException e) {
            return ResultVo.failed(400, "您没有得到相应的授权！" + e.getMessage(), null);
        }

    }

    @RequestMapping(value = "/logout")
    public String logout() {
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Session session = SecurityUtils.getSubject().getSession();
        UserInfo u = (UserInfo) session.getAttribute("userInfo");
        return "退出登录成功" + u;
    }

    /***
     * 验证码校验
     * @param request 请求
     * @param response 相应
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 在这里进行验证码的校验
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Session session = SecurityUtils.getSubject().getSession();
        // 取出验证码
        String validateCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("session中的验证码：" + validateCode);
        // 取出页面的验证码
        String randomcode = httpServletRequest.getParameter("captchaCode");
        System.out.println("网页输入的验证码：" + randomcode);
        // 输入的验证和session中的验证进行对比
        if (validateCode != null && randomcode != null && !"".equals(randomcode) && !"".equals(validateCode)) {
            if (validateCode.equals(randomcode)) {
                return true;
            }
        }
        return false;
    }
}
